import e, { Request, Response, Router, urlencoded, json } from 'express';
import account_router from './account.router.js';
import * as todoService from '../services/todo.service.js';
import * as accountService from '../services/account.service.js';
import { Responses } from '../utils/responses.js';
// 引入 cors 中间件
import cors from 'cors';
import { sleep } from '../utils/time.js';

const router: Router = Router();
// const corsOptions = {
//   origin: 'http://localhost:5173', // 只允许来自https://example.com的请求
//   methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // 允许的HTTP方法
//   preflightContinue: false,
//   optionsSuccessStatus: 204 // 对于OPTIONS请求返回的状态码
// };

// 使用 cors 中间件
// router.use(cors(corsOptions)); 
router.use(cors());

router.use(urlencoded({ extended: true }));
router.use(json());
// 根路由

router.use(async (req: Request, res: Response, next) => {
  console.log('',req.method,' ', req.path);
  await sleep(500)
  next();
})
router.get('/', async (req: Request, res: Response) => {
  try {
    // 获取todos
    let todos = await todoService.paginateTodos(0,1, 5);
    let user = await accountService.getUsersByPage(1, 5);
    let data = {
      todos: todos.items,
      users: user.items
    };
    res.send(Responses.success(data, ''));
  } catch (error) {
    // 这里应该是 res.send 而不是 Responses.error
    res.status(400).send(Responses.error([], error.message));
  }
});



// 注册路由
router.post('/account/register', async (req: Request, res: Response) => {
  try {
    const { username, password, description = '' } = req.body;
    // await sleep(500)
    await accountService.register(username, password, description)
    res.send(Responses.success(req.body, '注册成功'));
  } catch (error) {
    res.status(400).send(Responses.error([], error.message));
  }
});

// 登录路由
router.post('/account/login', async (req: Request, res: Response) => {
  const { username, password } = req.body;
  const user = await accountService.login(username, password)
  if (user) {
    const { password, ...rest } = user

    res.send(Responses.success(rest, '登录成功'));
  } else {
    res.status(400).send(Responses.error([], '登录失败'));
  }
});

// 获取用户列表
router.get('/users', async (req: Request, res: Response) => {
  try {
    let { page, username } = req.query;
    page = page as string
    username = (username as string).trim()
    if (page.trim() === '') {
      page = '1'
    }

    let users = await accountService.getUsersByPage(parseInt(page), 3, username);
    res.send(Responses.success(users, ''));
  } catch (error) {
    res.status(400).send(Responses.error([], error.message));
  }


});

// 获取 todos 列表
router.get('/todos', async (req: Request, res: Response) => {
  //获取query参数
  try {
    let { page = 1, title = '', completed = undefined } = req.query;
    let finished = undefined
    if (completed !== undefined) {
      finished = parseInt(completed as string)
      if (Number.isNaN(finished)) {
        finished = undefined
      }
    }
    if (page !== 1) {
      page = parseInt(page as string)
      if (Number.isNaN(page)) {
        page = 1
      }
    }
    if (title !== '') {
      title = title as string
    }
    const todos = await todoService.paginateTodos(0,page, 3, title, finished);
    res.send(Responses.success(todos, ''));
  } catch (error) {
    res.status(400).send(Responses.error([], error.message));
  }
});

// 获取指定 id 的 todo
router.get('/todos/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    let todo = await todoService.getTodoById(parseInt(id))
    if (todo) {
      res.send(Responses.success(todo, ''));
    }
    else {
      res.status(400).send(Responses.error([], 'Todo项不存在'));
    }
  } catch (error) {
    res.status(400).send(Responses.error([], error.message));
  }
});
// 获取指定 id 的 user
router.get('/users/:id', async (req: Request, res: Response) => {
  const { id } = req.params;
  const user = await accountService.getUserById(parseInt(id))
  if (user) {
    res.send(Responses.success(user, ''));
  } else {
    res.status(400).send(Responses.error([], '用户不存在'));
  }
})

router.use('/', account_router);



export default router;
